package com.abc.xxx.config.security;

import com.abc.xxx.util.Result;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import static org.apache.commons.lang3.StringUtils.isNotBlank;

public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest req,
                         HttpServletResponse res,
                         AuthenticationException ex) throws IOException, ServletException {
        System.out.println("ex: "+ex);
        String jwtError = (String)req.getAttribute("jwtError");
        Result json = Result.error("filter")
                .msg(isNotBlank(jwtError)?jwtError:"未登录")
                .data("exception", ex.getMessage());
        res.setStatus(401);
        res.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        res.getWriter().write(json.toString());

    }

}
